﻿using System;
using System.Linq;
using System.Web;
using Se.Framework.Common;
using Se.Framework.Common.Data;
using Se.Framework.Common.Security;

namespace Se.Framework.Web
{
    public class WebSessionUserDataProvider<TUserData> : IUserDataProvider<TUserData>
        where TUserData : class, IUserData
    {
        public virtual TUserData CurrentUserData
        {
            get
            {
                TUserData user = HttpContext.Current.Session["currentUser"] as TUserData;
                if (user == null)
                {
                    var key = ObjectRegistry.Current.Resolve<IUserKeyProvider>().GetCurrentUserKey();
                    if (key == null)
                    {
                        throw new Exception("There is no user information available.");
                    }
                    user = CreateUser(key);
                }
                return user;
            }
        }

        private TUserData CreateUser(object key)
        {
            TUserData user = ObjectRegistry.Current.Resolve<TUserData>();
            user.Load(key);
            HttpContext.Current.Session["currentUser"] = user;
            return user;
        }

        public virtual void LoginUser(object key)
        {
            CreateUser(key);
        }

        public virtual void LogoutUser()
        {
            HttpContext.Current.Session["currentUser"] = null;
        }
    }
}